package com.boxin.ims.modules.wechat.busi;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.ad.entity.Advertisement;
import com.boxin.ims.modules.ad.service.AdvertisementService;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.wechat.entity.BusinessNewsReply;
import com.boxin.ims.modules.wechat.entity.ImageMessage;
import com.boxin.ims.modules.wechat.entity.LocationMessage;
import com.boxin.ims.modules.wechat.entity.Lottery;
import com.boxin.ims.modules.wechat.entity.LotteryLog;
import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.TextMessage;
import com.boxin.ims.modules.wechat.entity.UserBusiness;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.BusinessNewsReplyService;
import com.boxin.ims.modules.wechat.service.LotteryLogService;
import com.boxin.ims.modules.wechat.service.LotteryRecordService;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.DataUtils;
import com.boxin.ims.modules.wechat.utils.SpringUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;


/**
 * @author Jakemanse
 * @date 2013-9-23
 * @function <p> 微信业务数据处理 基类</p>
 */
public abstract class BusinessProcessor {
	
	protected final Logger logger = Logger.getLogger(this.getClass());
	
	
	protected String receiveMsg;	//用户发的消息信息
	protected String sendMsg;		//给 用户发送的数据信息
	protected User user;			//所属店家
	protected WeChat weChat;		//平台配置对象
	protected String openId;		//微信用户开放Open ID
	protected boolean isNeedMember;	//是否需要是会员
	protected HttpServletRequest request;	//页面请求对象
	protected HttpServletResponse response;	//写页面对象
	protected String url;					//是否
	
	protected Map<String,String> messageMap ;
	protected TextMessage textMessage;			//文本消息包装对象
	protected LocationMessage locationMessage;	//位置消息
	
	protected Map<String,Object> varMap = new HashMap<String,Object>();	//参数变数传递使用
	
	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	AdvertisementService advertisementService;

	@Autowired
	LotteryLogService  lotteryLogService;
	
	@Autowired
	LotteryRecordService lotteryRecordService;
	
	
	@Autowired
	BusinessNewsReplyService businessNewsReplyService;
	
	public BusinessProcessor(){
		
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-11  下午10:28:25
	 * @function <p> 检查该会员是否已经绑定，如果没有绑定直接回复 </p>
	 * @return
	 */
	public WechatMember  memberCheckAndReply(){
		
		WechatMember member =	wechatMemberService.getByWechatMemberId(user, openId);
		if(member == null){
			//String reply = "亲，您还不是我们的会员请<a href=\"http://weixin.zhaotang.net/zt/f/wechat/bind/"+user.getId() +"?wechatId="+openId+"&topage=scoreexchange\">点我申请微会员</a>谢谢！";
			//writeToUser(reply);
			
			String title = "微会员申请";
			UserDefine userDefine = WechatUtils.getUserDefineByUserId(weChat.getUser().getId());
			if(userDefine != null && StringUtils.isNotEmpty(userDefine.getRegMemberTitle())){
				title = userDefine.getRegMemberTitle();
			}
			
			String desc = "亲,您还不是我们的微会员,点击图片进入微会员申请页面赶紧注册成微会员吧。成为我们的会员后，您将可以参与各种优惠活动以及更好的服务,谢谢!";
			if(userDefine != null && StringUtils.isNotEmpty(userDefine.getRegMemberDesc())){
				desc = userDefine.getRegMemberDesc();
			}
			
			String picName = "reg.jpg";
			if(userDefine!=null && StringUtils.isNotEmpty(userDefine.getRegMemberPic())){
				picName = userDefine.getRegMemberPic();
			}
			String picUrl = "http://weixin.zhaotang.net/zt/userfiles/images/"+picName;
			picUrl ="http://weixin.zhaotang.net/zt/userfiles/images/"+picName+"?t="+System.currentTimeMillis();
			
			String url =  "http://weixin.zhaotang.net/zt/f/member/bind?uid="+user.getId() +"&wechatId="+openId;
				   url =  "http://weixin.zhaotang.net/zt/f/wechat/bind/"+user.getId() +"?wechatId="+openId;
				   
				   picUrl ="http://weixin.zhaotang.net/zt/userfiles/images/"+picName+"?t="+System.currentTimeMillis();
				   url = "http://weixin.zhaotang.net/zt/f/member/bind?uid="+user.getId() +"&wechatId="+openId;
					
			writeLinkImageToUser(title, desc, picUrl, url);
			
		}
		return member;
	}
	
	public void imageToUser(String mediaId){
		ImageMessage imageMessage = new ImageMessage(messageMap);
		try {
			String reply = imageMessage.imgMessage(mediaId);
			System.out.println(reply);
			response.getWriter().print(reply );
			logger.info(reply);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-21  上午11:06:02
	 * @function <p> 包装我的广告内容回复  </p>
	 * @param advertList
	 * @return
	 */
	public List<NewsReply>  generateAdvertNewsReplies(List<Advertisement> advertList){
		List<NewsReply> newsReplyList = new ArrayList<NewsReply>();
		if(advertList!=null && !advertList.isEmpty()){
			for(Advertisement ad:advertList){
				NewsReply newsReply = new NewsReply();
				newsReply.setArticleCount(1);
				newsReply.setCreateTime(new Date());
				newsReply.setDescription(ad.getDescription());
				newsReply.setFilePath(ad.getPicName());
				newsReply.setPicUrl("http://weixin.zhaotang.net/zt/userfiles/advert/"+ad.getPicName());
				newsReply.setUrl("http://weixin.zhaotang.net/zt/f/advert/view?id="+ad.getId()+"&uid="+user.getId()+"&wechatId="+openId+"&lotteryId="+ad.getTempId());
				if(com.thinkgem.jeesite.common.utils.StringUtils.isNotEmpty(newsReply.getUrl())){
					newsReply.setUrl(newsReply.getUrl());
				}
				newsReply.setTitle(ad.getTitle());
				
				newsReplyList.add(newsReply);
				
			}
		}
		
		return newsReplyList; 
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-21  上午11:41:45
	 * @function <p> 生成广告奖品及回复信息 </p>
	 * @return
	 */
	public List<NewsReply>  advertisementServicesNewsList(){
		List<Advertisement> adList = findMyAdvertisement(user.getId());
		//判断该会员是否需要得到该广告奖品
		List<Advertisement> replyAdList = new ArrayList<Advertisement>();
		if(adList!=null && !adList.isEmpty()){
			WechatMember member = getMember();
			for(Advertisement admt : adList){
				//
				int repeatCount = admt.getRepeatCount();
				
				
				LotteryLog query = new LotteryLog();
				query.setMember(member);
				query.setSourceId(admt.getId());
				query.setUser(user);
				
				long count =0;
				
				
				if(admt.getRepeatCycleCount()==null||"".equals(admt.getRepeatCycleCount())){
					count = lotteryLogService.findLotteryLogCount(query);
				}else{
					if("1".equals(admt.getRepeatCycleCount())){		//周
						query.setCreateTime(com.thinkgem.jeesite.common.utils.DateUtils.getNowWeekBegin());
						count=lotteryLogService.findLotteryLogCountByWeeks(query);
					}
					
					if("2".equals(admt.getRepeatCycleCount())){		//月
						query.setCreateTime(com.thinkgem.jeesite.common.utils.DateUtils.getMonthFirstDay());
						count=lotteryLogService.findLotteryLogCountByMonth(query);
					}
				}
				
				
				if(repeatCount>count){
					
					LotteryRecord lottery = new LotteryRecord();
					lottery.setName(admt.getName());
					lottery.setSourceType(LotteryRecord.SURCE_TYPE_ADVERT);
					lottery.setMember(member);
					lottery.setUser(user);
					lottery.setSourceId(admt.getId());
					if(admt.getValidCycleEndday()==null||"".equals(admt.getValidCycleEndday())){
						lottery.setEndTime(DateUtils.getDelayDate(admt.getValidDays()));
					}else{
						if("1".equals(admt.getValidCycleEndday())){		//当周
							lottery.setEndTime(com.thinkgem.jeesite.common.utils.DateUtils.getNowWeekEnd());
						}
						
						if("2".equals(admt.getValidCycleEndday())){		//当月
							lottery.setEndTime(com.thinkgem.jeesite.common.utils.DateUtils.getMonthLastDay());
						}
					}
					
					
					System.out.println("设置endTime:"+com.thinkgem.jeesite.common.utils.DateUtils.getMonthLastDay());
					
					if(lottery.getEndTime() == null){	//默认为月
						lottery.setEndTime(com.thinkgem.jeesite.common.utils.DateUtils.getMonthLastDay());
					}
					
					lottery.setStatus(Lottery.STATUS_NORMAL);
					lottery.setRemarks(user.getName()+"的会员【"+member.getName()+"】获取广告主"+admt.getAdvertiser().getName()+"的奖品--"+admt.getName());
					
					lotteryRecordService.save(lottery);
					
					admt.setTempId(lottery.getId());
					replyAdList.add(admt);		//生成广告奖品
					
					
					//生成奖品日志
					LotteryLog log = new LotteryLog();
					log.setMember(member);
					log.setType(LotteryRecord.SURCE_TYPE_ADVERT);
					log.setSourceId(admt.getId());
					log.setName(admt.getName());
					log.setRemarks(user.getName()+"的会员【"+member.getName()+"】获取广告主"+admt.getAdvertiser().getName()+"的奖品--"+admt.getName());
					log.setStatus(LotteryRecord.STATUS_NORMAL);
					log.setUser(user);
					
					lotteryLogService.save(log);
				}
				
				
			}
		}
		
		
		
		return generateAdvertNewsReplies(replyAdList);
		
	}
	
	
	
	public List<Advertisement> findMyAdvertisement(Long userId){
		return advertisementService.findSellerAdList(userId);
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-5-4  下午2:18:43
	 * @function <p> 图文回复列表 </p>
	 * @param member
	 * @param userBusiness
	 * @return
	 */
	protected List<NewsReply> findNewsMessage(WechatMember member,UserBusiness userBusiness ){
		List<NewsReply> newsReplies = new ArrayList<NewsReply>();
		List<BusinessNewsReply>	bnrList = businessNewsReplyService.findByTypeSourceId("business", user.getId() , userBusiness.getId()+"");
		if(bnrList != null  && !bnrList.isEmpty() ){
			
			newsReplies = DataUtils.convertToNewsReplyList(bnrList);
			if(newsReplies!=null  && !newsReplies.isEmpty()){
				for(NewsReply newsReply : newsReplies){
					String title = newsReply.getTitle();
					
					if(member!=null){
						
						int finalScore = member.getScore();
						if(StringUtils.isNotEmpty(title)){
							title = title.replaceAll("%积分%", finalScore/1000+"");
							title = title.replaceAll("%连续签到%", member.getSignupCount()+"");
							if(0==member.getSignupCount()){
								member.setSignupCount(1);
							}
							title = title.replaceAll("%连续签到%", member.getSignupCount()+"");
							newsReply.setTitle(title);
						}
						
						
						String desc = newsReply.getDescription();
						desc = desc.replaceAll("%积分%", finalScore/1000+"");
						desc = desc.replaceAll("%连续签到%", member.getSignupCount()+"");
						newsReply.setDescription(desc);
					}
					
					
					
				}
			}
		}
		
		
		//更新URL 将系统中动态的参数值补充到URL中
		replaceUrlParameters(newsReplies);
		
		
		return newsReplies;
		
		
		
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-11  下午11:20:43
	 * @function <p>  </p>
	 * @return
	 */
	public WechatMember getMember(){
		return wechatMemberService.getByWechatMemberId(user, openId);
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-25  下午2:24:36
	 * @function <p> 查询用户的服务 </p>
	 * @return
	 */
	public UserBusiness  getUserBusiness(){
		return WechatUtils.getUserBusinessByKeyWords(user.getId(),getTextMessage().getContent());
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-25  下午2:25:50
	 * @function <p> 获得 UserDefine </p>
	 * @return
	 */
	public UserDefine getUserDefine(){
		return WechatUtils.getUserDefineByUserId(user.getId());	//定义
	}
	
	
	
	public BusinessProcessor(WeChat weChat,String openId,HttpServletRequest request,HttpServletResponse response){
		this.weChat = weChat;
		this.openId = openId;
		this.request = request;
		this.response = response;
		this.user = weChat.getUser();
	}
	
	public BusinessProcessor(WeChat weChat,String openId){
		this.weChat = weChat;
		this.openId = openId;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-25  下午2:37:37
	 * @function <p> 返回本业务 的多图文  </p>
	 * @return
	 */
	public  List<BusinessNewsReply>	 getBusinessMultiNews(){
		try {
			BusinessNewsReplyService businessNewsReplyService = (BusinessNewsReplyService) SpringUtils.getBean("businessNewsReplyService");
			List<BusinessNewsReply>	bnrList = businessNewsReplyService.findByTypeSourceId("business", user.getId() , getUserBusiness().getId()+"");
			return bnrList;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-7  上午12:45:53
	 * @function <p> 向中奖用户发送电子凭证 </p>
	 * @param title
	 * @param desc
	 * @param qrcodeId
	 */
	public void writeImageToUser(String title,String desc,Long qrcodeId){
		ImageMessage imageMessage = new ImageMessage(messageMap);
		imageMessage.setArticleCount("1");
		imageMessage.setTitle(title);
		imageMessage.setDescription(desc+ getQrcodeMessage());
		imageMessage.setPicUrl(QRCodeUtils.getQRCodePNGURL(qrcodeId));
		imageMessage.setUrl(QRCodeUtils.getQRCodePNGPageURL(qrcodeId)+"&uid="+getUser().getId());
		try {
			String reply = imageMessage.replyMessage();
			response.getWriter().print(reply );
			logger.info(reply);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-19  下午4:31:30
	 * @function <p> 回复单图 </p>
	 * @param title
	 * @param desc
	 * @param url
	 * @param siteUrl
	 */
	public void writeImageToUser(String title,String desc,String  url,String siteUrl){
		ImageMessage imageMessage = new ImageMessage(messageMap);
		imageMessage.setArticleCount("1");
		imageMessage.setTitle(title);
		imageMessage.setDescription(desc);
		imageMessage.setPicUrl(url);
		
		siteUrl  = replaceUrlParameters(siteUrl);
		imageMessage.setUrl(siteUrl);
		try {
			String reply = imageMessage.replyMessage();
			response.getWriter().print(reply );
			logger.info(reply);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-12  下午1:12:26
	 * @function <p> 查询奖品回复内容 </p>
	 * @param title
	 * @param desc
	 * @param qrcodeId
	 */
	public void writeSingleLotteryImageToUser(String title,String desc,Long qrcodeId){
		ImageMessage imageMessage = new ImageMessage(messageMap);
		imageMessage.setArticleCount("1");
		imageMessage.setTitle(title);
		imageMessage.setDescription(desc+ getQrcodeMessage());
		imageMessage.setPicUrl(QRCodeUtils.getQRCodePNGURL(qrcodeId));
		imageMessage.setUrl(QRCodeUtils.getQRCodePNGPageURL(qrcodeId));
		try {
			String reply = imageMessage.replyMessage();
			response.getWriter().print(reply );
			logger.info(reply);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-1-28  下午10:37:07
	 * @function <p>全局通知信息  </p>
	 * @return
	 */
	private String getQrcodeMessage(){
		
		UserDefine userDefine =	WechatUtils.getUserDefineByUserId(user.getId());
		if(userDefine != null && com.thinkgem.jeesite.common.utils.StringUtils.isNotEmpty(userDefine.getQrcodeMessage())){
			return userDefine.getQrcodeMessage();
		}
		return "";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-25  下午2:29:37
	 * @function <p> 替换 图文回复时 的URL 的动态参数 </p>
	 * @param newsReplies
	 */
	public  void replaceUrlParameters(List<NewsReply> newsReplies){
		
		if(newsReplies != null && !newsReplies.isEmpty()){
			
			System.out.println("newsReplies.size():"+newsReplies.size()+"============");
			int i =0;
			for(NewsReply reply : newsReplies){
				if(reply == null){
					System.out.println("newsReplies.size():  reply == null    "+(i++)+"============");
					continue;
				}else{
					System.out.println("newsReplies.size():++++   "+(i++)+"============");
					String url = reply.getUrl();
					if(StringUtils.isNotEmpty(url)){
						url = url.replaceAll("%uid%", user.getId()+"");
						url = url.replaceAll("%wid%", openId);
					}
					reply.setUrl(url);					
				}
				
			}
		}
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-26  下午3:26:08
	 * @function <p> 处理替换URL </p>
	 * @param url
	 * @return
	 */
	public String replaceUrlParameters(String url){
		if(StringUtils.isNotEmpty(url)){
			url = url.replaceAll("%uid%", user.getId()+"");
			url = url.replaceAll("%wid%", openId);
		}
		return url;
	}
	
	
	
	
	public void writeQueryLotteryImageToUser( List<NewsReply> newsReplyList){
		ImageMessage imageMessage = new ImageMessage(messageMap);
		try {
			String reply = imageMessage.replyMessage(newsReplyList);
			response.getWriter().print(reply );
			logger.info(reply);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-1-16  下午4:50:59
	 * @function <p> 多图文回复 </p>
	 * @param newsReplyList
	 */
	public void writeMultiImagesToUser( List<NewsReply> newsReplyList){
		ImageMessage imageMessage = new ImageMessage(messageMap);
		try {
			replaceUrlParameters(newsReplyList);
			
			String reply = imageMessage.replyMessage(newsReplyList);
			response.getWriter().print(reply );
			logger.info(reply);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
	public void writeImageXMLToUser(String xml){
		try {
			response.getWriter().print(xml );
			logger.info(xml);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	/**
	 * @author Jakemanse
	 * @time 2013-10-7  上午12:49:55
	 * @function <p> 导航连接图片 </p>
	 * @param title	图片标题
	 * @param desc  图片描述
	 * @param picUrl	图片地址
	 * @param url		图片连接地址
	 */
	public void writeLinkImageToUser(String title,String desc,String picUrl,String url){
		ImageMessage imageMessage = new ImageMessage(messageMap);
		imageMessage.setArticleCount("1");
		imageMessage.setTitle(title);
		imageMessage.setDescription(desc );
		imageMessage.setPicUrl(picUrl);
		imageMessage.setUrl(url);
		try {
			String reply = imageMessage.replyMessage();
			response.getWriter().print(reply );
			logger.info(reply);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-2  上午9:27:36
	 * @function <p>回复用户信息  </p>
	 * @param reply
	 */
	public void writeToUser(String reply){
		//返回给微信用户的信息
		try {
			TextMessage txtMsg = new TextMessage(messageMap);
			txtMsg.setContent(reply +  getQrcodeMessage());
			response.getWriter().print(txtMsg.replyMessage() );
			logger.info(txtMsg.replyMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-3  上午9:07:15
	 * @function <p> 未到所有关键词的回复，则回配置的默认内容 </p>
	 */
	public void writeDefaultToUser(){
		writeToUser(weChat.getRemarks()) ;
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-23  下午11:04:29
	 * @function <p> 消息处理后的返回结果 </p>
	 * @return
	 */
	public abstract ProcessMessage process();
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-2  下午3:24:57
	 * @function <p> 是否必须要求是会员 </p>
	 * @return
	 */
	public abstract boolean isNeedBeMember();
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-3  上午8:43:01
	 * @function <p> 写调试信息  </p>
	 * @param reply
	 */
	public void printReplyLogger(String reply){
		logger.debug("回复的全内容是:"+reply);
	}
	
	
	
	
	

	public LocationMessage getLocationMessage() {
		return locationMessage;
	}

	public void setLocationMessage(LocationMessage locationMessage) {
		this.locationMessage = locationMessage;
	}

	public String getReceiveMsg() {
		return receiveMsg;
	}

	public void setReceiveMsg(String receiveMsg) {
		this.receiveMsg = receiveMsg;
	}

	public String getSendMsg() {
		return sendMsg;
	}

	public void setSendMsg(String sendMsg) {
		this.sendMsg = sendMsg;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


	public WeChat getWeChat() {
		return weChat;
	}

	public void setWeChat(WeChat weChat) {
		this.weChat = weChat;
	}

	public String getOpenId() {
		return openId;
	}

	public void setOpenId(String openId) {
		this.openId = openId;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public Map<String, String> getMessageMap() {
		return messageMap;
	}

	public void setMessageMap(Map<String, String> messageMap) {
		this.messageMap = messageMap;
	}

	public TextMessage getTextMessage() {
		return textMessage;
	}

	public void setTextMessage(TextMessage textMessage) {
		this.textMessage = textMessage;
	}

	public Logger getLogger() {
		return logger;
	}
	
	public void setNeedMember(boolean isNeedMember){
		this.isNeedMember = isNeedMember;
	}

	public String getUrl() {
		
		
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map<String, Object> getVarMap() {
		return varMap;
	}

	public void setVarMap(Map<String, Object> varMap) {
		this.varMap = varMap;
	}
	
	
	
	

}
